#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <stdlib.h>

#define NUM 1024

struct MyFILE_
{
    int fd;//文件描述符
    char buffer[NUM];//缓冲区
    int end;//当前缓冲区结尾
};

typedef struct MyFILE_ MyFILE;

MyFILE* fopen_(const char* pathname,const char* mode)
{
    assert(pathname);
    assert(mode);

    MyFILE* fp = NULL;

    if(strcmp(mode,"r") == 0)
    {

    }
    else if(strcmp(mode,"r+") == 0)
    {

    }
    else if((strcmp(mode,"w") == 0))
    {

        int fd = open(pathname,O_WRONLY | O_TRUNC | O_CREAT,0666);
            if(fd >= 0)
            {
              fp = (MyFILE*)malloc(sizeof(MyFILE));
              memset(fp,0,sizeof(MyFILE));

              fp->fd = fd;

            }
    }
    else if(strcmp(mode,"w+") == 0)
    {
        
    }
    else if(strcmp(mode,"a") == 0)
    {

    }
    else if(strcmp(mode,"a+") == 0)
    {

    }

    return fp;
}

void fputs_(const char* str,MyFILE* fp)
{
    assert(str);
    assert(fp);
    
    //将数据写入缓冲区
    strcpy(fp->buffer + fp->end,str);
    fp->end += strlen(str);//更新缓冲区结尾
    
    //printf("%s",fp->buffer);
    //向标准输入，输出，错误中打印
    if(fp->fd == 0)
    {

    }
    else if(fp->fd == 1)
    {
        if(fp->buffer[fp->end - 1] == '\n')
        {
            write(fp->fd,fp->buffer,fp->end);
            fp->end = 0;
        }
    }
    else if(fp->fd == 2)
    {

    }
    else 
    {

    }

}

void fflush_(MyFILE* fp)
{
    assert(fp);
    if(fp->end != 0)
    {
        write(fp->fd,fp->buffer,fp->end);
        //将内核数据写入磁盘
        syncfs(fp->fd);
        fp->end = 0;
    }
}

void fclose_(MyFILE* fp)
{
    assert(fp);
    fflush_(fp);
    
    close(fp->fd);
    free(fp);
    fp = NULL;
}



int main()
{
    MyFILE* fp = fopen_("log.txt","w");
    if(fp == NULL)
    {
        perror("fopen_");
        return 1;
    }
    
    fputs_("hello linux",fp);
    fputs_("hello linux\n",fp);
    fputs_("hello linux",fp);
    fputs_("hello linux\n",fp);

    
    fclose_(fp);
    return 0;
}


